import './index.less';
import { FC, useContext, useEffect, useState } from "react";
import { Modal, Image, ImageViewer } from "antd-mobile";
import { Button, Space, Toast, WaterMark, Dialog, Typography, Tag } from 'react-vant';
import { getNote, getNoteCount, getPayData } from '../../../../api';
import { useRequest } from 'ahooks';
import { copy, wxPay } from '../../../../utils/utils';
import notesvg from '../../../../assets/note.svg';
import "animate.css";
import { useNavigate } from 'react-router-dom';
import { Arrow } from '@react-vant/icons';
import { appStoreContext } from '../../../../App';

interface IProps {
    showFollow: () => void;
}

type statistic = {
    maleCount: number;
    femaleCount: number;
    unknownCount: number;
}
type NoteInfoType = {
    account?: string
    accountType: string
    content?: string
    createTs: string
    imageIds?: { url: string }[]
    imgs?: string[]
    pushUserId: string
    sex: string
    _id: string
}
const Box: FC<IProps> = ({ showFollow }) => {
    const [boxClass, setBoxClass] = useState<string>('box');
    const [noteInfo, setNoteInfo] = useState()
    const [loading, setLoading] = useState<boolean>(false)

    const navigate = useNavigate();

    const showModal = (noteInfo: any) => {
        console.log(noteInfo)
        if (noteInfo.wxQrCode) {
            ImageViewer.show({
                image:noteInfo.wxQrCode,
                renderFooter: () => {
                    return (
                        <div className='text-center pb10'>
                            <Tag color='default' className='px10 py7' round>长按二维码可直接添加</Tag>
                        </div>
                    )
                }
            })
        } else {
            Modal.show({
                image: noteInfo.imageIds[0].url || 'https://gw.alipayobjects.com/mdn/rms_efa86a/afts/img/A*SE7kRojatZ0AAAAAAAAAAAAAARQnAQ',
                showCloseButton: true,
                closeOnAction: true,
                title: noteInfo.nickName,
                actions: [
                    {
                        key: 'share',
                        text: '复制账号',
                        onClick: () => {
                            copy(noteInfo.account);
                            Toast('账号复制成功');
                        }
                    },
                ],
                content: (
                    <>
                        <div>性别：{noteInfo.sex == '0' ? '男' : '女'}</div>
                        <div>账号：{noteInfo.account} ({noteInfo.accountType == 'wx' ? '微信' : 'QQ'})</div>
                        <div>备注：{noteInfo.content || '--'}</div>
                        <div>投递时间：{noteInfo.createTs}</div>
                        {/* <WaterMark content={noteInfo.account}/> */}
                    </>
                )
            })
        }
    }

    const onFollow = () => {
        showFollow();
    }

    let appStore = useContext(appStoreContext)

    const getNoteService = async (params: { sex: string }) => {
        console.log(params)

        setLoading(true)
        setAnimateClass('animate__animated animate__shakeX')
        setTimeout(() => {
            setBoxClass('box box-open');
        }, 1200);

        setTimeout(async () => {
            try {
                let res = await getNote(params);

                if (res.data?.noPushHistory) {
                    Dialog.confirm({
                        title: '温馨提示',
                        message: res.msg,
                        confirmButtonText: '现在去投',
                        cancelButtonText: '等会再去',
                    })
                        .then(() => {
                            navigate('/pushNote');
                        })
                        .catch(() => {
                            console.log('catch');
                        })
                } else if (res.data?.noCount) {
                    Dialog.confirm({
                        confirmButtonText: '立即支付',
                        cancelButtonText: '查看优惠',
                        message: (
                            <div>
                                <p>您没有可用抽/取次数</p>
                                <p>支付￥1获取一个 {params.sex == '1' ? '女' : '男'} 生缘分</p>
                                {!userInfo.isSubscribe && <Typography.Text type="danger">
                                    <small>（关注可免费获取一次机会）</small>
                                    <Tag type="warning" onClick={() => { onFollow() }}>去关注 <Arrow /></Tag>
                                </Typography.Text>}
                            </div>
                        ),
                    }).then(() => {
                        console.log('confirm')
                        wxPay({ orderType: 'count', pullkey: 'C1' }, () => { getNoteService({ sex: params.sex }) });
                    })
                        .catch(() => {
                            navigate('/my')
                        })

                } else {
                    setNoteInfo({ ...res.data })
                    showModal(res.data)
                }

                setBoxClass('box');
                setAnimateClass('')
                setLoading(false)

            } catch (error) {
                setLoading(false)
            }
        }, 1500);
    }

    const { run } = useRequest(getNoteService, {
        manual: true,
        throttleWait: 3000
    });

    const [noteCount, setNoteCount] = useState<statistic>({
        maleCount: 0,
        femaleCount: 0,
        unknownCount: 0,
    });

    const [userInfo, setUserInfo] = useState<any>(false);

    useEffect(() => {
        getNoteCount().then(res => {
            setNoteCount(res.data);
        }).catch(err => {
            console.log(err)
        })
        sessionStorage.getItem('userInfo') && setUserInfo(JSON.parse(sessionStorage.getItem('userInfo') as string))
    }, [])

    const [animateClass, setAnimateClass] = useState<string>('animate__animated animate__bounce');

    return (
        <>
            <div className={animateClass}>
                <div className={boxClass} onClick={() => { }}>
                    <div className="side front">
                        <p>CP BOX</p>
                        <small>实时数量:{noteCount.maleCount + noteCount.femaleCount + noteCount.unknownCount + 1000}</small>
                    </div>
                    <div className="side back"></div>
                    <div className="side left"></div>
                    <div className="side right"></div>
                    <div className="side top">
                        <div className="tl">
                            <p>男生</p>
                            <small>{noteCount.maleCount + 500}张</small>
                        </div>
                        <div className="tr">
                            <p>女生</p>
                            <small>{noteCount.femaleCount + noteCount.unknownCount + 500}张</small>
                        </div>
                    </div>
                    <div className="side bottom"></div>
                    <div className="text">
                        <Image src={notesvg} alt="" />
                    </div>
                </div>
            </div>
            <Space justify='center' block>
                <div>
                    <Button round plain type='primary' loading={loading} style={{ width: '120px' }} onClick={() => {
                        run({ sex: '0' })
                    }}>
                        找男生
                    </Button>
                    <p style={{ fontWeight: 200, color: '#fff', textAlign: 'center' }}>
                        <small>{noteCount.maleCount + 500}张可抽</small>
                    </p>
                </div>
                <div>
                    <Button round plain color='#f17783' loading={loading} style={{ width: '120px' }} onClick={() => {
                        run({ sex: '1' })
                    }}>
                        找女生
                    </Button>
                    <p style={{ fontWeight: 200, color: '#fff', textAlign: 'center' }}>
                        <small>{noteCount.femaleCount + noteCount.unknownCount + 500}张可抽</small>
                    </p>
                </div>
            </Space>
        </>
    );
}

export default Box